<template>
	<div class="publish-button global-display global-j-end">
		<van-button type="success" size="small" @click="reLease" :disabled="disabled">发布</van-button>
	</div>
	<van-field class="input-size" v-model="title" maxlength="30" size="large" placeholder="好的标题更容易被推荐(必填)" />
	<van-field
		class="input-size"
		v-model="content"
		rows="6"
		autosize
		size="large"
		type="textarea"
		placeholder="分享有趣或想吐槽的经历,帮助更多热爱旅行的人(必填)"
		@blur="blurEvent"
	/>
	<div class="upload-img">
		<van-uploader v-model="fileList" max-count="6" multiple accept=".jpg,.jpeg,.png,.webp,.jfif"
		:before-delete="beforeDelete"
		/>
	</div>
	<div class="location-view">
		<van-divider />
		<div class="address global-display global-a-items" @click="mapShow = true">
			<p>你在哪里</p>
			<p class="text-show">{{poiname}}</p>
			<van-icon name="arrow" color="#919191" size="20"/>
		</div>
	</div>
	<!-- 已添加的标签 -->
	<div class="location-view" v-if="myLabel.length > 0">
		<p class="tag-Text">还可添加{{numberTags - myLabel.length}}个标签</p>
		<van-tag class="vanTag" v-for="(item,index) in myLabel" color="#ec6f97" closeable round size="medium" type="primary" @close="close(index,item)">
		  {{item}}
		</van-tag>
	</div>
	<!-- 选择标签 -->
	<div class="location-view">
		<p class="tag-Text">推荐标签</p>
		<van-tag class="vanTag" v-for="(item,index) in recLabel" 
		:color="item.active ? '#ec6f97' : '#f3f4f6'" 
		:text-color="item.active ? '#ffffff' : '#000000'" 
		round size="medium" type="primary"
		@click="addTag(item)"
		>
		  {{item.name}}
		</van-tag>
		<van-tag color="#ec6f97" plain round size="medium" type="primary" @click="tagTrue = true">
		  + 自定义标签
		</van-tag>
	</div>
	<!-- 自定义标签弹窗 -->
	<van-dialog :show="tagTrue" title="自定义标签" show-cancel-button
	@confirm="tagConfirm"
	@cancel="tagTrue = false"
	>
	  <van-field size="large" placeholder="请输入自定义标签" autofocus v-model="customTag" />
	</van-dialog>
	<!-- 地图选点 -->
	<van-popup v-model:show="mapShow" position="bottom">
		<iframe id="mapPage" frameborder=0
		    :src="mapUrl">
		</iframe>
	</van-popup>
  <div style="height: 300px;"></div>
  <tabbar/>
</template>

<script setup>
import tabbar from '@/page/Tabbar/index.vue'
import { ref,watch,watchEffect } from 'vue'
import request from '@/api/request.js'
import {LBS_KEY} from '@/api/my-account.js'
import { showToast,showLoadingToast } from 'vant';
import emitter from '@/api/event.js'
import {compressImage} from '@/api/compression.js'
import {upLoadCos} from '@/api/cos.js'
import { useRouter } from 'vue-router'
const $router = useRouter()  // 这是路由跳转的
const mapUrl = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&&key=${LBS_KEY}&referer=myapp`
// 游记标题
const title = ref('')
// 游记内容
const content = ref('')
// 暂存展示的图片
const fileList = ref([]);
// 删除指定的图片
function beforeDelete(file,detail){
	fileList.value.splice(detail.index,1)
	// const key = [...forms.keys()].find(key => forms.get(key) === file.file);
}
//显示||隐藏：地图
const mapShow = ref(false)
// 选中的市和位置
const cityname = ref('昆明市')
const poiname = ref('昆明市')
const province = ref('云南省昆明市')
// 接收选中位置的回调
window.addEventListener('message', (event)=> {
	// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
	const loc = event.data;
	// console.log(loc);
	if (loc && loc.module == 'locationPicker') {
	  cityname.value = loc.cityname
	  poiname.value = loc.poiname == '我的位置' ? loc.cityname : loc.poiname
	  province.value = loc.poiaddress
	  mapShow.value = false
	}
}, false);
// 推荐标签
const recLabel = ref([])
// 我选中的标签
const myLabel = ref([])
// 设置可以添加几个标签
const numberTags = ref(10)
// 自定义标签
const customTag = ref('')
// 自定义标签弹窗:显示||隐藏
const tagTrue = ref(false)
// 写文章失去焦时触发：分析文章关键词
async function blurEvent(){
	const res = await request.post('/article_keyword', {text:content.value});
	if(res.data.length > 0){
		res.data.forEach(item=>{
			if (!recLabel.value.some((el) => el.name === item)) {
			    recLabel.value.push({name:item,active:false});
			}
		})
	}
}
// 添加标签
function addTag(tag) {
	if(myLabel.value.length >= 10){
		showToast({message:'最多只能添加10个标签',duration:800});
		return
	}
	if (!tag.active) {
		myLabel.value.push(tag.name);
		// 设置标签为选中状态
		tag.active = true;
	}
}
// 删除标签
function close(index,tag){
	myLabel.value.splice(index,1)
	// 设置标签为未选中状态
	const recTag = recLabel.value.find((item) => item.name === tag);
	if (recTag) {
	  recTag.active = false;
	}
}
// 去除换行符和回车符
watch(customTag,(newValue,oldValue) => {
  customTag.value = customTag.value.trim().replace(/[\r\n]/g, '');
});
// 选择自定义标签触发
function tagConfirm(){
	tagTrue.value = false
	if(myLabel.value.length >= 10){
		showToast({message:'最多只能添加10个标签',duration:800});
		return
	}
	if(customTag.value == '')return
	const res_a = myLabel.value.find(item=>item === customTag.value)
	if(res_a){
		showToast({message:'相同标签只能存在一个',duration:800});
		return false
	}
	const res_b = recLabel.value.find(item=>item.name === customTag.value)
	if(res_b){
		showToast({message:'推荐标签已存在',duration:800});
		return false
	}
	myLabel.value.push(customTag.value);
}

// FormData上传-----暂时不需要
/* 
const config = {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
};
const forms = new FormData()
forms.delete('file')
comressRes.forEach(item=>forms.append('file', item)) 
await request.post('/image_upload', forms, config);
*/
// 监听必填值是否填写完毕
const disabled = ref(true)
watchEffect(()=>{
	const hasData = title.value && content.value && fileList.value.length > 0 && myLabel.value.length > 0;
	disabled.value = hasData ? false : true
})
// 发布
async function reLease(){
	const toast1 = showLoadingToast({
	  message: '发布中...',
	  forbidClick: true,
	  duration:0
	});
	const comressRes = await compressImage(fileList.value)
	try{
		// 是否登录校验
		await request.get('/check_login');
		const upLoadRes = await upLoadCos(comressRes)
		const param = {
			title:title.value,
			content:content.value,
			city:cityname.value,
			address:poiname.value,
			province:province.value,
			tag:myLabel.value,
			image:upLoadRes
		}
		await request.post('/article_publish', param);
		title.value = ''
		content.value = ''
		myLabel.value = []
		recLabel.value = []
		fileList.value = []
		emitter.emit('release-success');// 发布成功触发
		toast1.close();
		$router.push('/')
	}catch(err){
		console.log(err);
		toast1.close();
	}
}
</script>

<style>
:root:root {
	--van-uploader-size:100px;
	--van-uploader-icon-color:#5e5f63;
	--van-uploader-upload-background:#f3f4f6;
	--van-tag-medium-padding:5px 10px;
	--van-button-small-padding:10px 30px;
	--van-button-small-font-size:16px;
}
.publish-button{
	padding: 10px;
}
.input-size{
	font-size: 17px;
}
.upload-img{
	padding: 10px 0 0 10px;
}
.location-view{
	padding: 10px;
}
.address{
	font-weight: bold;
}
.address img{
	width: 20px;
	height: 20px;
}
.address p:nth-child(2){
	flex: 1;
	padding: 0 20px;
	color: #ffd01e;
}
.vanTag{
	margin-right: 5px;
}
.tag-Text{
	color: #bbbbbb;
	padding-bottom: 10px;
	font-weight: bold;
}
#mapPage{
	width: 100%;
	height: 100vh;
}
</style>